package com.authine.cloudpivot.web.api.secondopen.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.web.api.config.HxConfig;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.secondopen.domain.AjaxResult;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6Fpsyjlxx;
import com.authine.cloudpivot.web.api.secondopen.domain.Monthlybudgetadjustrecord;
import com.authine.cloudpivot.web.api.secondopen.domain.OcrInvoice;
import com.authine.cloudpivot.web.api.secondopen.service.ReimburseService;
import com.authine.cloudpivot.web.api.secondopen.utils.HttpRestUtil;
import com.authine.cloudpivot.web.api.utils.DateUtil;
import com.authine.cloudpivot.web.api.utils.HttpClientUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import io.jsonwebtoken.lang.Collections;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.asm.Advice;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * ocr发票识别
 *
 */
@Api(value = "二开接口", tags = "ocr发票识别")
@RestController
@RequestMapping("/api/ocrInvoice")
public class OrcInvoiceController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(OrcInvoiceController.class);

    @Autowired
    private HxConfig hxConfig;

    @Autowired
    private ReimburseService reimburseService;

    @RequestMapping(value="/ocrInvoiceData",method = {RequestMethod.POST ,RequestMethod.GET })
    @ApiOperation(value = "orc识别发票信息", notes = "orc识别发票信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "图片路径", dataType = "String", paramType = "query")
    })
    public AjaxResult ocrInvoiceData(@RequestParam(value = "url", required = false) String url) throws ParseException {
//        url="D:\\fp.jpg";
        List<OcrInvoice> ocrInvoices=new ArrayList<>();
        try {
            ocrInvoices=postBase64(getImgStr(url));
            log.info("----------识别发票数据：-----------{}",JSON.toJSONString(ocrInvoices));
            if(Collections.isEmpty(ocrInvoices)){
                return AjaxResult.error(300,"未识别到发票数据");
            }
//            this.truthVerificationFp(ocrInvoices);
        } catch (Exception e) {
            log.info("识别发票失败：",e);
            e.printStackTrace();
        }
        return AjaxResult.success(ocrInvoices);
    }

    public static String getImgStr(String imgFile){
         //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
         InputStream in = null;
         byte[] data = null;
         //读取图片字节数组
         try
         {
//             in = new FileInputStream(imgFile);
//             data = new byte[in.available()];
//             in.read(data);
//             in.close();
             URL httpUrl = new URL(imgFile);
             HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
             conn.setRequestMethod("GET");
             conn.setConnectTimeout(5 * 1000);
             InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
             data= readInputStream(inStream);//得到图片的二进制数据
         }
         catch (Exception e) {
             e.printStackTrace();
         }
        return new String(Base64.encodeBase64(data));
    }


    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public List<OcrInvoice> postBase64(String str_base64) throws ParseException {
        String url = hxConfig.getOrcurl();

        //设置请求参数

        Map<String, String> params = new HashMap<>();

        params.put("app_key", hxConfig.getAppkey());

        params.put("app_secret", hxConfig.getAppsecret());

        params.put("crop_image", hxConfig.getCropimage());
        //设置识别图像base64编码
        params.put("image_base64", str_base64);
        params.put("do_query", "1");
        //发送请求，得到识别结果
        String result = HttpClientUtil.doPost(url, params);
        JSONObject jsonObject = JSONObject.parseObject(result);

        List<OcrInvoice> ocrInvoices=new ArrayList<>();
        if(result!=null) {
            JSONArray jsonArray = jsonObject.getJSONArray("result");
            log.info("**result列表接口返回:{}", jsonArray);
            if (jsonArray != null && jsonArray.size() > 0) {
                int size = jsonArray.size();
                for (int i = 0; i < size; i++) {
                    JSONObject resultObject = (JSONObject) jsonArray.get(i);
                    OcrInvoice ocrInvoice=new OcrInvoice();
                    //发票类型
                    String fplxCode=resultObject.getString("type");

                    //发票类型
                    String fplx=resultObject.getString("type_msg");
                    //发票消费类型对应的中文名
                    String fpxflx=resultObject.getString("expense_type_msg");
                    //发票描述
                    String fpyt="";
                    JSONObject recognizeObj=JSONObject.parseObject(resultObject.getString("recognize_result"));

                    //纳税人识别号
                    String nsrsbh="";
                    if(fplx.indexOf("增值税") == 0){
                        JSONObject buyTaxJson = JSONObject.parseObject(recognizeObj.getString("buyer_tax_id"));
                        if(buyTaxJson != null){
                            //key:纳税号 + _行号  value：发票抬头
                            nsrsbh=buyTaxJson.getString("item_words");
                        }

                    }

                    //发票描述
                    if(fplx.indexOf("增值税") != -1){
                        fpyt=JSONObject.parseObject(recognizeObj.getString("buyer_name")).getString("item_words");
                    }else if("火车票".equals(fplx) || "客运票".equals(fplx)){
                        String city1=JSONObject.parseObject(recognizeObj.getString("station_from")).getString("item_words");
                        String city2=JSONObject.parseObject(recognizeObj.getString("station_to")).getString("item_words");
                        fpyt=city1+"--"+city2;
                    }else if("航空运输电子客票行程单".equals(fplx)){
                        JSONArray flightsArray=recognizeObj.getJSONArray("flights");
                        if (flightsArray != null && flightsArray.size() > 0) {
                            JSONObject flightsObj=((JSONObject) flightsArray.get(0));
                            String city1=((JSONObject)flightsObj.get("from")).getString("item_words");
                            String city2=((JSONObject)flightsObj.get("to")).getString("item_words");
                            fpyt=city1+"--"+city2;
                        }
                    }else if("过路费发票".equals(fplx)){
                        String city1=JSONObject.parseObject(recognizeObj.getString("entrance")).getString("item_words");
                        String city2=JSONObject.parseObject(recognizeObj.getString("exit")).getString("item_words");
                        fpyt=city1+"--"+city2;
                    }else if("出租车票".equals(fplx)){
                        fpyt=JSONObject.parseObject(recognizeObj.getString("place")).getString("item_words");
                    }

                    //发票号
                    String fph="";
                    //发票代码
                    String fpdm="";
                    if("航空运输电子客票行程单".equals(fplx)){
                        fph=JSONObject.parseObject(recognizeObj.getString("e_ticket_no")).getString("item_words");
                    }else{
                        JSONObject invoiceCode=JSONObject.parseObject(recognizeObj.getString("invoice_no"));
                        JSONObject invoiceDm=JSONObject.parseObject(recognizeObj.getString("invoice_code"));
                        if(invoiceCode!=null){
                            fph=invoiceCode.getString("item_words");
                        }
                        if(invoiceDm!=null){
                            fpdm=invoiceDm.getString("item_words");
                        }
                    }

                    //校验码
                    String checkCode="";
                    JSONObject checkCodeObj=JSONObject.parseObject(recognizeObj.getString("check_code"));
                    if(checkCodeObj!=null){
                        checkCode=checkCodeObj.getString("item_words");
                    }


                    String yskpDate="";
                    JSONObject kpDateObj=JSONObject.parseObject(recognizeObj.getString("date"));
                    if(kpDateObj!=null){
                        //开票日期
                        yskpDate=kpDateObj.getString("item_words");
                    }




                    //税率
                    String shuilv="";
                    //税额
                    String shuie="";
                    //未税金额
                    String wsje="";
                    //票据金额
                    String pjje="";
                    //发票日期
                    String pjDate="";



                    //增值税普通发票明细
                    JSONArray jsonDetailArray = recognizeObj.getJSONArray("details");

                    //是 "增值税电子发票" 并且有税率和税额(网约车的特殊处理)
                    if("增值税普通发票".equals(fplx) || "增值税电子普通发票".equals(fplx)){
                        if (jsonDetailArray != null && jsonDetailArray.size() > 0) {
                            for (int j = 0; j < jsonDetailArray.size(); j++) {
                                JSONObject jsonDetailObj = (JSONObject) jsonDetailArray.get(j);
                                if(jsonDetailObj!=null){
                                    String mc=JSONObject.parseObject(jsonDetailObj.getString("name")).getString("item_words");
                                    //内容不是运输服务费
                                    if(mc.indexOf("*运输服务") == -1){
                                        //税率税额都赋值为 0
                                        shuilv="0";
                                        shuie="0";
                                        JSONObject amountLittleObj = JSONObject.parseObject(recognizeObj.getString("amount_little"));
                                        if(amountLittleObj!=null){
                                            String taxTotal=amountLittleObj.getString("item_words");
                                            if(StringUtils.isNotBlank(taxTotal)){
                                                wsje=taxTotal;
                                            }else{
                                                wsje="0";
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }


                    //税额
//                    if(StringUtils.isBlank(shuie)){
                    if(("增值税专用发票".equals(fplx) || "增值税普通发票".equals(fplx) || "增值税电子普通发票".equals(fplx) || "增值税电子专用发票".equals(fplx)) && jsonDetailArray!=null && jsonDetailArray.size() >0 && jsonDetailArray.size() <2){
                        JSONObject jsonDetailObj = (JSONObject) jsonDetailArray.get(0);
                        if(jsonDetailObj!=null){
                            shuie=JSONObject.parseObject(jsonDetailObj.getString("tax")).getString("item_words");
                        }
                    }else if(("增值税专用发票".equals(fplx) || "增值税普通发票".equals(fplx) || "增值税电子普通发票".equals(fplx) || "增值税电子专用发票".equals(fplx)) && jsonDetailArray!=null && jsonDetailArray.size() >1){
                        Double element = 0.0;
                        for (int a = 0; a < jsonDetailArray.size(); a++) {
                            JSONObject jsonDetailObj = (JSONObject) jsonDetailArray.get(a);
                            if(jsonDetailObj!=null){
                                String tax=JSONObject.parseObject(jsonDetailObj.getString("tax")).getString("item_words");
                                Double taxDoube=0.0;
                                try {
                                    taxDoube=Double.valueOf(tax);
                                }catch (Exception e){
                                    taxDoube=0.0;
                                }
                                element=element + taxDoube;
                            }
                        }
                        shuie=String.valueOf(element);
                    }
//                    }

                    //未税金额
                    if(StringUtils.isBlank(wsje)){
                        if("增值税专用发票".equals(fplx)){
                            JSONObject pretaxAmount=JSONObject.parseObject(recognizeObj.getString("pretax_amount"));
                            if(pretaxAmount!=null){
                                wsje=pretaxAmount.getString("item_words");
                            }
                        }
                    }

                    //票据金额
                    JSONObject amountLittleObj = JSONObject.parseObject(recognizeObj.getString("amount_little"));
                    if(amountLittleObj != null){
                        if(StringUtils.isBlank(amountLittleObj.getString("item_words"))){
                            pjje="0";
                        }else{
                            pjje=amountLittleObj.getString("item_words");
                        }
                    }


                    //税率
//                    if(StringUtils.isBlank(shuilv)){
                        if(fplx.indexOf("增值税") != -1 && jsonDetailArray!=null && jsonDetailArray.size() == 1){
                            JSONObject jsonDetailObj= (JSONObject) jsonDetailArray.get(0);
                            if(jsonDetailObj!=null){
                                JSONObject jsontaxRateObj= (JSONObject)jsonDetailObj.get("tax_rate");
                                if(jsontaxRateObj!=null){
                                    shuilv=jsontaxRateObj.getString("item_words");
                                }

                            }
                        }else if(fplx.indexOf("增值税") != -1 && jsonDetailArray!=null && jsonDetailArray.size() > 1){
                            Double element = 0.0;
                            for (int a = 0; a < jsonDetailArray.size(); a++) {
                                JSONObject jsonDetailObj = (JSONObject) jsonDetailArray.get(a);
                                if(jsonDetailObj!=null){
                                    String tax=JSONObject.parseObject(jsonDetailObj.getString("tax")).getString("item_words");
                                    Double taxDoube=0.0;
                                    try {
                                        taxDoube=Double.valueOf(tax);
                                    }catch (Exception e){
                                        taxDoube=0.0;
                                    }
                                    element=element + taxDoube;
                                }
                            }
                            if(amountLittleObj!=null){
                                String taxTotal=amountLittleObj.getString("item_words");
                                //税率=税额合计/票据金额
                                shuilv = String.valueOf(element/Double.valueOf(taxTotal));
                            }else{
                                shuilv="0";
                            }
                        }else if("火车票".equals(fplx) || "航空运输电子客票行程单".equals(fplx)){
                            shuilv="0.09";
                        }else if("客运票".equals(fplx)){
                            shuilv="0.03";
                        }else{
                            shuilv="0";
                        }
//                    }

                    //发票日期
                    if("定额发票".equals(fplx)){
                        //定额发票没有发票时间
                        pjDate="";
                    }else if("火车票".equals(fplx)){
                        JSONObject dateTimeObj = JSONObject.parseObject(recognizeObj.getString("date_time"));
                        if(dateTimeObj != null){
                            pjDate = dateTimeObj.getString("item_words");
                        }
                    }else if("航空运输电子客票行程单".equals(fplx)){
                        JSONObject dateTimeObj = JSONObject.parseObject(recognizeObj.getString("date_of_issue"));
                        if(dateTimeObj != null){
                            pjDate = dateTimeObj.getString("item_words");
                        }
                    }else if("客运票".equals(fplx)){
                        JSONObject dateTimeObj = JSONObject.parseObject(recognizeObj.getString("date"));
                        if(dateTimeObj != null){
                            pjDate = dateTimeObj.getString("item_words");
                        }
                    }else if("过路费发票".equals(fplx)){
                        JSONObject dateTimeObj = JSONObject.parseObject(recognizeObj.getString("time"));
                        if(dateTimeObj != null){
                            pjDate = dateTimeObj.getString("item_words");
                        }
                    }else {
                        JSONObject dateTimeObj = JSONObject.parseObject(recognizeObj.getString("date"));
                        if(dateTimeObj != null){
                            pjDate = dateTimeObj.getString("item_words");
                        }
                    }
                    int shui=shuilv.indexOf("%");
                    if(shui != -1){
                        shuilv=String.valueOf(Double.valueOf(shuilv.substring(0,shuilv.indexOf("%")))/100);
                    }
                    //如果税额为空，但是税率和票据金额不为空，那么税额就等于，票据金额*税率
                    if(StringUtils.isBlank(shuie) && StringUtils.isNotBlank(shuilv) && StringUtils.isNotBlank(pjje)){
                        if("火车票".equals(fplx) || "航空运输电子客票行程单".equals(fplx) || "客运票".equals(fplx)){
                            Double shuieDouble=Double.valueOf(pjje)/(1+Double.valueOf(shuilv))*Double.valueOf(shuilv);
                            shuie=String.valueOf(this.formatDouble(shuieDouble));
                        }else{
                            shuie=String.valueOf(Double.valueOf(pjje)*Double.valueOf(shuilv));
                        }
                    }

                    if(StringUtils.isNotBlank(shuie) && StringUtils.isNotBlank(pjje)){

                        try {
                            Double a=Double.valueOf(shuie);
                        }catch (Exception e){
                            shuie="0";
                        }
                        wsje=String.valueOf(Double.valueOf(pjje)-Double.valueOf(shuie));
                    }

                    ocrInvoice.setFpms(fpyt);
                    ocrInvoice.setPjlx(fplx);
                    if(pjDate.indexOf("年")!=-1 && pjDate.indexOf("月")!=-1 && pjDate.indexOf("日")!=-1){
                        ocrInvoice.setKpDate(DateUtil.convertDate(pjDate));
                    }else{
                        ocrInvoice.setKpDate(pjDate);
                    }

                    try {
                        Double b=Double.valueOf(shuilv);
                    }catch (Exception e){
                        shuilv="0";
                    }
                    //查验结果
                    JSONObject queryResultObj=JSONObject.parseObject(resultObject.getString("query_result"));
                    if(queryResultObj!=null){
                        String desc=queryResultObj.getString("desc");
                        String description=queryResultObj.getString("description");
                        if(desc!=null){
                            ocrInvoice.setCheckInfo(desc);
                            String resultCode=queryResultObj.getString("result_code");
                            if(resultCode!=null){
                                ocrInvoice.setCheckCode(resultCode);
                            }
                        }else if(description!=null){
                            ocrInvoice.setCheckInfo(description);
                        }else{
                            ocrInvoice.setCheckInfo("该发票不支持验真");
                        }
                    }else{
                        ocrInvoice.setCheckInfo("该发票不支持验真");
                    }


                    ocrInvoice.setFph(fph);
                    ocrInvoice.setPjje(pjje);
                    ocrInvoice.setSl(shuilv);
                    if(StringUtils.isNotBlank(shuilv)){
                        Double sl=Double.valueOf(shuilv)*100;
                        ocrInvoice.setSl(sl.toString());
                    }
                    ocrInvoice.setShuie(shuie);
                    ocrInvoice.setWsje(wsje);
                    ocrInvoice.setFpxflx(fpxflx);
                    ocrInvoices.add(ocrInvoice);
//                    if(StringUtils.isNotEmpty(fplxCode)){
//                        if("10100".equals(fplxCode)){
//                            fplxCode="01";
//                        }else if("".equals(fplxCode)){
//                            fplxCode="";
//                        }else if("10104".equals(fplxCode)){
//                            fplxCode="03";
//                        }else if("10101".equals(fplxCode)){
//                            fplxCode="04";
//                        }else if("10102".equals(fplxCode)){
//                            fplxCode="10";
//                        }else if("10103".equals(fplxCode)){
//                            fplxCode="11";
//                        }else if("".equals(fplxCode)){
//                            fplxCode="";
//                        }else if("10105".equals(fplxCode)){
//                            fplxCode="15";
//                        }
//                    }
//                    ocrInvoice.setInvoiceType(fplxCode);
//                    ocrInvoice.setInvoiceCode(fpdm);
//                    ocrInvoice.setCheckCodeLast(checkCode);
//                    ocrInvoice.setCreateDate(yskpDate);


//                    JSONObject kpDateObj=JSONObject.parseObject(recognizeObj.getString("date"));
//                    //开票日期
//                    String kpDate=kpDateObj.getString("item_words");
//                    kpDate=DateUtil.convertDate(kpDate);
//
//                    //票据金额
//                    JSONObject pretaxAmount=JSONObject.parseObject(recognizeObj.getString("pretax_amount"));
//                    String pjje=pretaxAmount.getString("item_words");
//                    //税率
//                    //增值税普通发票明细
//                    JSONArray jsonDetailArray = recognizeObj.getJSONArray("details");
//                    log.info("**jsonDetailArray列表接口返回:{}", jsonDetailArray);
//                    if (jsonDetailArray != null && jsonDetailArray.size() > 0) {
//                        JSONObject jsonDetailObj= (JSONObject) jsonDetailArray.get(0);
//                        if(jsonDetailObj!=null){
//                            JSONObject jsonDetailObj2= (JSONObject)jsonDetailObj.get("tax_rate");
//                            String itemWords=jsonDetailObj2.getString("item_words");
//                        }
//                    }
//
//                    //税额
//                    JSONObject taxAmount=JSONObject.parseObject(recognizeObj.getString("tax_amount"));
//                    String shuie=kpDateObj.getString("item_words");
                }

            }
        }
        return ocrInvoices;
    }

    /**
     * 保留两位小数，四舍五入
     * @param d
     * @return
     */
    public static double formatDouble(double d) {
        return (double)Math.round(d*100)/100;
    }


    public List<OcrInvoice> truthVerificationFp(List<OcrInvoice> ocrInvoices) throws ParseException {
        if(!Collections.isEmpty(ocrInvoices)){
            for (OcrInvoice ocrInvoice : ocrInvoices) {
                String url = hxConfig.getOrcjyurl();

                //设置请求参数

                Map<String, String> params = new HashMap<>();

                params.put("app_key", hxConfig.getAppkey());

                params.put("app_secret", hxConfig.getAppsecret());

                params.put("invoice_type", ocrInvoice.getInvoiceType());

                params.put("invoice_no", ocrInvoice.getFph());

                params.put("invoice_code", ocrInvoice.getInvoiceCode());
                String checkCodeLast=ocrInvoice.getCheckCodeLast();
                if(StringUtils.isNotEmpty(checkCodeLast)){
                    params.put("check_code_last6", checkCodeLast.substring(checkCodeLast.length() - 6));
                }
                params.put("total", ocrInvoice.getPjje());

                params.put("create_date", ocrInvoice.getCreateDate());

                //发送请求，得到识别结果
                String result = HttpClientUtil.doPost(url, params);
                JSONObject jsonObject = JSONObject.parseObject(result);

                if(result!=null) {
                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                    log.info("**result列表接口返回:{}", jsonArray);
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject resultObject = (JSONObject) jsonArray.get(0);
                        int resultCode=resultObject.getInteger("result_code");
                        if("1".equals(resultCode)){
                            ocrInvoice.setCheckInfo("查验成功");
                        }else if("2".equals(resultCode)){
                            ocrInvoice.setCheckInfo("超过该张票当天查验次数");
                        }else if("6".equals(resultCode)){
                            ocrInvoice.setCheckInfo("查验成功发票不一致");
                        }else if("9".equals(resultCode)){
                            ocrInvoice.setCheckInfo("所查发票不存在");
                        }else if("105".equals(resultCode)){
                            ocrInvoice.setCheckInfo("查询发票不规范");
                        }else if("106".equals(resultCode)){
                            ocrInvoice.setCheckInfo("查验异常");
                        }

                    }
                }
            }
        }

        return ocrInvoices;
    }


    /**
     * 提交前判断发票号是否重复
     *
     */
    @PostMapping("/submitPdfpxx")
    public AjaxResult submitPdfpxx(@RequestBody String[] fphs){
        log.info("---------------submitPdfpxx方法：fphs："+ JSON.toJSONString(fphs));
        if(fphs==null || fphs.length==0){
//            log.info("---------------方法：getBudgetQuotaByParam参数：年份："+qnyssq.getNf()+"，总账户编码："+qnyssq.getOneaccountcode()+",分帐户编码："+qnyssq.getTwoaccountcode()+"，成本中心："+qnyssq.getYscbzx());
            return AjaxResult.success("无发票信息数据");
        }
        //查询发票号数据
        List<Ie6s6Fpsyjlxx> ie6s6Fpsyjlxxes=reimburseService.getFpDeatailByParam(fphs);
        log.info("---------------返回信息："+ JSON.toJSONString(ie6s6Fpsyjlxxes));
        if(!Collections.isEmpty(ie6s6Fpsyjlxxes)){
            String fph="";
            for (Ie6s6Fpsyjlxx ie6s6Fpsyjlxx : ie6s6Fpsyjlxxes) {
                if(StringUtils.isBlank(fph)){
                    fph=ie6s6Fpsyjlxx.getFph();
                }else{
                    fph=fph+"，"+ie6s6Fpsyjlxx.getFph();
                }
            }
            return AjaxResult.error(300,"提交失败，存在已使用的发票号："+fph);
        }
        return AjaxResult.success("允许提交，发票未使用");
    }


    /**
     * 报销提交后插入发票信息数据
     *
     * @param objId
     * @return
     */
    @RequestMapping(value="/submitBxPreInsertFpData",method = {RequestMethod.POST ,RequestMethod.GET })
    @ApiOperation(value = "报销提交后插入发票信息数据", notes = "报销提交后插入发票信息数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "objId", value = "业务对象id", dataType = "String", paramType = "query")
    })
    public void submitBxPreInsertFpData(String objId,String processCode,String identtify) {
        log.info("获取参数:objId={},processCode={},identtify={}", objId,processCode,identtify);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode) || StringUtils.isBlank(identtify)) {
            log.info("参数不完整，直接结束");
            return;
        }
        String processName="";
        String tableName="";
        if("wbxcbxdlc".equals(processCode)){
            processName="外埠行车报销单";
            tableName="wbxcfpSheet";
        }else if("clfbxlc".equals(processCode)){
            processName="差旅费报销单";
            tableName="jtgjfpsheet,ssbzfpSheet,snjtfpSheet";
        }else if("lxpjbxlc".equals(processCode)){
            processName="零星票据报销流程";
            tableName="lxbxfpSheet";
        }else if("hksqdlc".equals(processCode)){
            processName="汇款申请单";
            tableName="hkfpSheet";
        }

        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return;
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }

        if("hksqdlc".equals(processCode)){
            String fklx = (String) bizObject.get("fklx");
            if(!"票到付款".equals(fklx)){
                log.info("{}付款为类型非票到付款，不进行发票信息维护，流程id为{}",processName,objId);
                return;
            }
        }

        String[] tName=tableName.split(",");
        for (String name : tName) {
            List<Map<String, Object>> bTableSheets=(List<Map<String, Object>>) bizObject.get(name);
            if(!Collections.isEmpty(bTableSheets)) {
                for (int i = 0; i < bTableSheets.size(); i++) {
                    String fph = String.valueOf(bTableSheets.get(i).get("fph"));
                    //如果是提交
                    if("1".equals(identtify)){
                        //则插入发票数据
                        Ie6s6Fpsyjlxx ie6s6Fpsyjlxx=converFpDetail(fph);
                        int num=reimburseService.addFpsyjlx(ie6s6Fpsyjlxx);
                    }else{
                        //驳回则删除发票数据
                        reimburseService.delFpsyjlxByFph(fph);
                    }
                }
            }
        }

    }

    private Ie6s6Fpsyjlxx converFpDetail(String fph) {
        Ie6s6Fpsyjlxx ie6s6Fpsyjlxx = new Ie6s6Fpsyjlxx();
        ie6s6Fpsyjlxx.setId(fph);
        ie6s6Fpsyjlxx.setCreater("");
        ie6s6Fpsyjlxx.setCreatedDeptId("");
        ie6s6Fpsyjlxx.setOwner("");
        ie6s6Fpsyjlxx.setOwnerDeptId("");
        ie6s6Fpsyjlxx.setCreatedTime(new Date());
        ie6s6Fpsyjlxx.setModifier("");
        ie6s6Fpsyjlxx.setModifiedTime(new Date());
        ie6s6Fpsyjlxx.setSequenceStatus("COMPLETED");
        ie6s6Fpsyjlxx.setOwnerDeptQueryCode("1");
        ie6s6Fpsyjlxx.setFph(fph);
        return ie6s6Fpsyjlxx;
    }




}
